export interface ICallbackData {
  currentFrame: number; // 当前帧编号
  time: number; // 时间展示，已经播放时长，单位是秒（s）
}

export interface IFrameData extends ICallbackData {
  totalFrame: number; // 总帧数
  timePerFrame: number; // 每帧显示时间
  repeat: '关' | '永远' | '迭代次数'; // 重复播放的类型
  gap: number; // 间隙
  iterations: number; // 迭代次数
}

type callbackType = (isPlaying: boolean, data: ICallbackData) => void;

/**
 * 帧动画
 */
export class FrameAnimation {
  // 播放数据
  private playData: IFrameData;

  // 定时器id
  private timerId: NodeJS.Timeout | null = null;
  private currentIteration: number = 0; // 当前迭代到第几次了

  /*
   * 开始播放
   * */
  public start = (frameData: IFrameData, callback: callbackType) => {
    this.playData = frameData;
    this.currentIteration = 0;
    const regularTime = frameData.timePerFrame * 1000; // s=>ms

    // 设置定时器
    this.timerId = setInterval(() => {
      let isPlaying = true;

      // 当前帧数大于等于总数时候
      if (this.playData.currentFrame >= this.playData.totalFrame) {
        // 如果超过，则总帧数赋值给当前帧数，否则等于赋予零
        if (this.playData.currentFrame > this.playData.totalFrame) {
          this.playData.currentFrame = this.playData.totalFrame;
        } else {
          this.playData.currentFrame = 0;
        }
        this.currentIteration += 1;
        switch (this.playData.repeat) {
          case '关':
            this.stop();
            isPlaying = false;
            break;
          case '迭代次数':
            if (this.currentIteration > this.playData.iterations) {
              this.stop();
              isPlaying = false;
            }
            break;
        }
      }
      const timeM = this.playData.currentFrame * this.playData.timePerFrame;

      const params = {
        currentFrame: this.playData.currentFrame,
        time: timeM,
      };
      callback(isPlaying, params);
      // 当前帧数小于总帧数的时候进行给当前帧数加间隙帧数，当回调完进行重置帧数。
      if (this.playData.currentFrame < this.playData.totalFrame) {
        this.playData.currentFrame += frameData.gap;
      }
    }, regularTime);
  };

  /*
   * 停止播放
   * */
  public stop = () => {
    clearInterval(this.timerId);
  };
}
